import { postlogin, finduserInfo } from '@/api/user'
import { getToken, setToken, setTokentime} from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  usertoken(state, newtoken) {
    state.token = newtoken
    setToken(newtoken)
  },
  setuserInfo(state,newuserInfo) {
    state.userInfo = newuserInfo
  }
}

const actions = {
  async login(context, { username, password }) {
    const {token} = await postlogin({
      username,
      password
    })
    setTokentime()
    context.commit('usertoken', token)
  },
  // 获取用户信息
  async getuserInfo (context) {
    const userInfo = await finduserInfo()
    context.commit('setuserInfo', userInfo)
  },
  // 退出登录
  logout (context) {
    context.commit ('usertoken', '')
    context.commit('setuserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

